package com.glacier.excel.utils;

import com.glacier.excel.annotation.ExcelIgnore;
import com.glacier.excel.annotation.ExcelIgnoreFields;
import com.glacier.excel.annotation.ExcelProperty;
import com.glacier.excel.domain.ExcelPropertyMeta;
import com.glacier.excel.domain.builder.ExcelPropertyMetaBuilder;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * date 2021-06-10 17:41
 *
 * @author glacier
 * @version 1.0
 */
public class ClassUtils {
    
    private ClassUtils() {
    }
    
    /**
     * 分析注解
     *
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> List<ExcelPropertyMeta> analysisField(Class<T> cls) {
        ExcelIgnoreFields ignoreFields = cls.getAnnotation(ExcelIgnoreFields.class);
        return Arrays.stream(cls.getDeclaredFields())
                .filter(field ->
                        field.getDeclaredAnnotation(ExcelProperty.class) != null
                                && field.getDeclaredAnnotation(ExcelIgnore.class) == null
                                && (ignoreFields == null || !Arrays.asList(ignoreFields.fields()).contains(field.getName()))
                )
                .map(field -> {
                            ExcelProperty property = field.getDeclaredAnnotation(ExcelProperty.class);
                            return ExcelPropertyMetaBuilder.anExcelPropertyMeta()
                                    .withField(field)
                                    .withValue(property.value())
                                    .withIndex(property.index())
                                    .withOrder(property.order())
                                    .withValidate(property.validate())
                                    .withWidth(property.width())
                                    .withConverter(property.converter())
                                    .build();
                        }
                )
                .sorted(Comparator.comparingInt(ExcelPropertyMeta::getIndex)
                        .thenComparing(ExcelPropertyMeta::getOrder)
                        .thenComparing(o -> o.getField().getName()))
                .collect(Collectors.toList());
    }
}
